import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/edit_remark/index.dart";
import "package:ct_pa_majordomo/pages/bill/widgets/show_multi_date_picker.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:image_picker/image_picker.dart";

class BillAccounting extends StatefulWidget {
  const BillAccounting({super.key});


  @override
  State<StatefulWidget> createState() => _BillAccountingState();

}

class _BillAccountingState extends State<BillAccounting> {
  Widget _required = Text("*", style: TextStyle(color: ThemeVars.colorError),);
  int _inoutFlag = 0;
  List<XFile>? _imageFile;
  late ImagePicker _imagePicker;
  Map _params = {
    "name": "",
    "money": "",
    "inoutFlag": 0,
    "billStartDate": DateTools.formatYMD(DateTime.now()),
    "billEndDate": DateTools.formatYMD(DateTime.now()),
    "payDate": DateTools.formatYMD(DateTime.now()),
    "remark": "",
  };

  Widget _radio({
    required int value,
    required String title,
    required int groupValue,
    required void Function(int) onChanged
  }) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        onChanged(value);
      },
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          groupValue == value
              ? Icon(Icons.check_circle, color: ThemeVars.colorPrimary, size: 18,)
              : Icon(Icons.circle_outlined, color: ThemeVars.colorPrimary, size: 18,),
          SizedBox(width: 2,),
          Text(title, style: TextStyle(fontSize: 14),)
        ],
      ),
    );
  }

  Widget _renderFace() {
    if (_imageFile != null && _imageFile!.isNotEmpty) {
      return Row(
        children: List.generate(_imageFile!.length * 2 - 1, (index) {
          if (index.isOdd) {
            return SizedBox(width: 6,);
          }
          XFile item = _imageFile![index ~/ 2];
          return Image.file(
            File(item.path),
            fit: BoxFit.cover,
            width: 100,
            height: 100,
          );
        }),
      );
    }
    return Container(
      width: 100,
      height: 100,
      decoration: BoxDecoration(
        color: ThemeVars.colorBackground,
      ),
      child: const Icon(Icons.add, size: 50,),
    );
  }

  Future<void> _pickImage() async {
    final pickedImage = await _imagePicker.pickMultiImage();
    if (pickedImage != null && pickedImage.length > 3) {
      pickedImage.removeRange(3, pickedImage.length);
    }
    if (pickedImage != null && pickedImage.isNotEmpty) {
      setState(() {
        _imageFile = pickedImage;
      });
    }
  }

  @override
  void initState() {
    _imagePicker = ImagePicker();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "记账",
      child: Stack(
        children: [
          ListView(
            children: [
              MenuBlock(
                borderRadius: BorderRadius.circular(0),
                items: [
                  MenuBlockItem(
                      text: "",
                      showArrow: false,
                      prefix: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          _radio(
                            title: "收入",
                            value: 0,
                            groupValue: _inoutFlag,
                            onChanged: (value) => setState(() {
                              _inoutFlag = value;
                            }),
                          ),
                          SizedBox(width: 10,),
                          _radio(
                            title: "支出",
                            value: 1,
                            groupValue: _inoutFlag,
                            onChanged: (value) => setState(() {
                              _inoutFlag = value;
                            }),
                          )
                        ],
                      )
                  ),
                  MenuBlockItem(
                      text: "费用名称",
                      showArrow: false,
                      prefix: _required,
                      suffix: TextFormField(
                        initialValue: _params["name"],
                        textAlign: TextAlign.right,
                        decoration: const InputDecoration(
                          hintText: "请输入",
                          hintStyle: TextStyle(fontWeight: FontWeight.w100, color: ThemeVars.colorTextTer),
                          isDense: true,
                        ),
                        onChanged: (value) => setState(() {
                          _params["name"] = value;
                        }),
                      )
                  ),
                  MenuBlockItem(
                      text: "记账金额",
                      showArrow: false,
                      prefix: _required,
                      suffix: TextFormField(
                        initialValue: _params["money"],
                        textAlign: TextAlign.right,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          hintText: "请输入",
                          hintStyle: TextStyle(fontWeight: FontWeight.w100, color: ThemeVars.colorTextTer),
                          isDense: true,
                        ),
                        onChanged: (value) => setState(() {
                          _params["money"] = value;
                        }),
                      )
                  ),
                  MenuBlockItem(
                      text: "账单周期",
                      prefix: _required,
                      suffix: Text("${_params["billStartDate"]} - ${_params["billEndDate"]}"),
                      onTap: () {
                        showMultiDatePicker(
                            context: context,
                            type: DateTimeType.range,
                            startDate: DateTime.parse(_params["billStartDate"]),
                            endDate: DateTime.parse(_params["billEndDate"]),
                            onchange: (dateRange) {
                              setState(() {
                                _params["billStartDate"] = dateRange[0];
                                _params["billEndDate"] = dateRange[1];
                              });
                            }
                        );
                      }
                  ),
                  MenuBlockItem(
                      text: "支付日期",
                      prefix: _required,
                      suffix: Text(_params["payDate"]),
                      onTap: () {
                        showDatetimePicker(
                            context: context,
                            initialDateTime: DateTime.parse(_params["payDate"]),
                            onchange: (date) {
                              setState(() {
                                _params["payDate"] = DateTools.formatYMD(date);
                              });
                            }
                        );
                      }
                  ),
                  MenuBlockItem(
                      text: "账单备注",
                      suffix: _params["remark"].isEmpty ? Text("请填写", style: TextStyle(color: ThemeVars.colorTextTer),) : Text(_params["remark"]),
                      onTap: () async {
                        Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                          return EditRemark(remark: _params["remark"]);
                        },),).then((value) {
                          if (value != null) {
                            setState(() {
                              _params["remark"] = value;
                            });
                          }
                        });
                      }
                  ),
                  MenuBlockItem(
                    text: "凭证图片",
                    showArrow: false,
                    tip: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _renderFace(),
                        const Text("(限3张图片，单张图片不超过10M，仅支持PNG/JPG格式)", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),)
                      ],
                    ),
                    // suffix: Icon(Icons.image_outlined),
                    onTap: _pickImage,
                  ),
                ],
              ),
            ],
          ),
          Positioned(
              left: 0,
              bottom: 30,
              width: MediaQuery.of(context).size.width,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
                child: Button(
                  type: ButtonType.primary,
                  child: Text("保存"),
                ),
              )
          )
        ],
      ),
    );
  }
}